#include "SDLAnimation.h"

SDLAnimation::SDLAnimation()
	:SDLSprite()
	, isDisorderSprite(false)
{
}
SDLAnimation::SDLAnimation( std::string fileName, int nbFrame, int frameRate, bool isLooping
						  , int srcX, int srcY, int srcW, int srcH, int dstX, int dstY, float size, bool isDisorder)
	: SDLSprite(fileName, srcX, srcY, srcW, srcH, dstX, dstY)
	, nbFrame(nbFrame)
	, frameRate(frameRate)
	, isLooping(isLooping)
	, isPlaying(false)
	, currentTime(0)
	, currentFrame(0)
	, initalSrcX(srcX)
	, isDisorderSprite(isDisorder)
	, sizeAnim(size)
{

}
SDLAnimation::~SDLAnimation()
{
	if(isDisorderSprite == true)
	{
		for(std::vector<SDL_Rect*>::iterator iter = listeSrcDisorderSprite.begin(); iter != listeSrcDisorderSprite.end(); iter++)
		{
			delete (*iter);
		}

		for(std::vector<SDL_Rect*>::iterator iter = listeDstDisorderSprite.begin(); iter != listeDstDisorderSprite.end(); iter++)
		{
			delete (*iter);
		}
	}
}
void SDLAnimation::Update()
{
	if(isPlaying)
	{
		currentTime += SDLTimer::GetInstance()->GetDeltaTime();
		if(currentTime >= 1.0f/frameRate)
		{
			currentFrame++;
			
			if(currentFrame > nbFrame)
			{
				if(isLooping)
				{
					currentFrame = 0;
				}
				else
				{
					isPlaying = false;
				}
			}

			if(isDisorderSprite == false)
			{
				SetSrcRect(initalSrcX + currentFrame * srcRect.w, srcRect.y, srcRect.w, srcRect.h);
				if(sizeAnim != 1.0f)
				{
					SetDstRect(dstRect.x, dstRect.y, srcRect.w * sizeAnim, srcRect.h * sizeAnim);
				}
			}
			else
			{
				SetSrcRect(listeSrcDisorderSprite[currentFrame -1]->x, listeSrcDisorderSprite[currentFrame -1]->y, listeSrcDisorderSprite[currentFrame -1]->w, listeSrcDisorderSprite[currentFrame -1]->h);
				if(sizeAnim != 1.0f)
				{
					SetDstRect(listeDstDisorderSprite[currentFrame -1]->x, listeDstDisorderSprite[currentFrame -1]->y, listeDstDisorderSprite[currentFrame -1]->w * sizeAnim, listeDstDisorderSprite[currentFrame -1]->h * sizeAnim);
				}
			}

			currentTime = 0;
		}
	}
}

void SDLAnimation::Play()
{
	isPlaying = true;
	currentFrame = 0;
}

void SDLAnimation::Stop()
{
	isPlaying = false;
}

void SDLAnimation::AddDisorderRect(int srcX, int srcY, int srcW, int srcH, int dstX, int dstY)
{
	SDL_Rect* rect = new SDL_Rect();
	rect->x = srcX;
	rect->y = srcY;
	rect->w = srcW;
	rect->h = srcH;
	listeSrcDisorderSprite.push_back(rect);

	rect = new SDL_Rect();
	rect->x = dstX;
	rect->y = dstY;
	rect->w = srcW;
	rect->h = srcH;
	listeDstDisorderSprite.push_back(rect);
}